<template>
  <div class="layout-warpper">
    <div class="layout-search">
      <div class="search-btns">
        <!-- 见证任务管理
BTN_RANDOM_ALLOCATE  随机分配
BTN_ASSIGN_ALLOCATE  定向分配
BTN_BATCH_APPROVE     批量审核 -->
        <!--
           -->
        <el-button
          v-if="$hasBtnsPerm('BTN_RANDOM_ALLOCATE')"
          :disabled="!hasStatusFn('UNASSIGNED')"
          type="primary"
          size="default"
          icon="icon-suiji1"
          @click="randomAssignFn"
        >
          随机分配
        </el-button>
        <el-button
          v-if="$hasBtnsPerm('BTN_ASSIGN_ALLOCATE')"
          :disabled="!hasStatusFn('UNASSIGNED')"
          type="primary"
          size="default"
          icon="icon-dingxiang1"
          @click="orientationAssignFn"
        >
          定向分配
        </el-button>
        <el-button
          v-if="$hasBtnsPerm('BTN_BATCH_APPROVE')"
          :disabled="!hasStatusFn('WITNESS_UN_REVIEWED')"
          type="primary"
          size="default"
          icon="icon-piliangshenhe1"
          @click="batchApproveFn"
        >
          批量审核
        </el-button>
      </div>
      <!--
        label-width="80px" -->
      <el-form
        ref="formSearch"
        :model="formSearch"
        :rules="rules"
        :inline="true"
        class="form-search font-right"
        size="normal"
      >
        <el-form-item label="开标时间" prop="date">
          <!--
            :picker-options="pickerOptions" -->
          <el-date-picker
            v-model="formSearch.date"
            type="daterange"
            align="left"
            style="width: 240px"
            unlink-panels
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleSearchFn"
          />
        </el-form-item>
        <el-form-item label="行业类别">
          <!--  -->
          <el-cascader
            v-model="formSearch.industry"
            option-max-width="100px"
            class="ui-w240"
            :props="{ multiple: true }"
            collapse-tags
            :collapse-tags-max-num="1"
            :tooltip-max-width="200"
            tooltip-effect="light"
            :options="TASKOBJ.industryTypeAndIndustry"
            @change="submitSearchFn"
          />
        </el-form-item>
        <!-- <el-form-item label="交易方式">
          <el-select
            v-model="formSearch.industry"
            class="ui-w120"
            value-key=""
            placeholder="请选择"
            clearable
            filterable
            @change="typeChangeFn"
          >
            <el-option
              v-for="item in industryTypeArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="见证状态">
          <el-cascader
            v-model="formSearch.status"
            option-max-width="300px"
            class="ui-w100"
            clearable
            :options="TASKOBJ.witnessSubTaskStatus"
            @change="submitSearchFn"
          />
        </el-form-item>
        <el-form-item label="" prop="keyWord">
          <!-- clearable -->
          <el-input
            v-model.trim="formSearch.keyWord"
            placeholder="项目名称/编号、标段名称/编号"
            class="ui-w320"
            @keydown="submitSearchFn"
          >
            <el-button slot="append" type="primary" icon="el-icon-search" @click="submitSearchFn" />
            <!-- <template slot="append"
              ><el-button type="primary" size="default" @click="submitSearchFn">
                <i class="el-input__icon el-icon-search"></i>
              </el-button>
            </template> -->
          </el-input>
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary" @click="onSubmit">立即创建</el-button>
        </el-form-item> -->
      </el-form>
    </div>
    <div class="ui-mb10 clear">
      <TopStatus class="float-right" type="manage" />
    </div>
    <!-- row-key="data.witnessTaskId"  :reserve-selection="true"-->
    <!-- {{ multipleSubTaskSelection }} -->
    <!-- 测试数据 start-->
    <!-- <span v-for="item in multipleTaskSelection" :key="item.data.witnessTaskId"
      >{{ item.data.witnessTaskId }},</span
    >
    ------
    <span
      v-for="item in multipleSubTaskSelection"
      :key="item.data.witnessSubTaskId"
      >{{ item.data.witnessSubTaskId }},</span
    > -->
    <!-- <span v-for="item in assignData" :key="item.data.witnessSubTaskId"
      >{{ item.data.witnessSubTaskId }},</span
    > -->
    <!-- 测试数据 end -->
    <!--
        @select="taskSelectClickFn"
        @select-all="taskSelectAllClickFn"
        @selection-change="handleTaskSelectionChangeFn" -->
    <div class="layout-body">
      <el-table
        ref="taskTable"
        :data="tableData"
        height="100%"
        :cell-class-name="tableRowClassName"
        stripe
        @expand-change="expandChangeFn"
        @select="taskSelectClickFn"
        @select-all="taskSelectAllClickFn"
      >
        <el-table-column type="selection" width="35" :selectable="subCheckboxSelectFns" />
        <el-table-column type="expand">
          <template slot-scope="props">
            <div class="ui-ml10">
              <!-- {{ props.row.data.witnessSubTaskInfoList.result }} -->
              <!--  -->
              <!-- <el-button
                type="primary"
                size="default"
                @click="toggleSelection(multipleSubTaskSelection, props.$index)"
                >选中</el-button
              > -->
              <!--  :reserve-selection="true" row-key="data.witnessSubTaskId"-->
              <!-- {{ props.row.data.witnessTaskId }} :key="props.row.data.witnessTaskId"-->
              <!--
                @selection-change="handleSubTaskSelectionChangeFn" -->
              <el-table
                :ref="'multipleTable_' + props.$index"
                :key="'multipleTable_' + props.$index"
                :data="props.row.data.witnessSubTaskInfoList.result"
                border
                stripe
                @select="subTaskSelectClickFn"
                @select-all="
                  (selection) => {
                    subTaskSelectAllClickFn(selection, props);
                  }
                "
              >
                <el-table-column type="selection" :selectable="subCheckboxSelectFn" width="55" align="center" />
                <!-- 第二页显示不对
                  :index="indexFn" -->
                <el-table-column type="index" align="center" label="序号" width="50" />
                <!-- <el-table-column
                  prop="data.witnessSubTaskId"
                  label="id"
                  width="190"
                >
                </el-table-column> -->
                <el-table-column prop="data.witnessSubTaskStatusEnum" label="任务阶段" width="90">
                  <template slot-scope="scope">
                    <span class="">
                      {{ scope.row.data.witnessSubTaskName }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="witnessSubTaskStatusEnum" label="任务状态" width="90">
                  <template slot-scope="scope">
                    <span class="task-tag">
                      <span :class="['', scope.row.data.witnessSubTaskStatusEnum]">
                        {{ witnessSubTaskStatusFn(scope.row.data.witnessSubTaskStatusEnum) }}
                      </span>
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="projectName" label="见证人" min-width="150">
                  <template slot-scope="scope">
                    <span v-if="scope.row.data.witnessUserName">
                      {{ scope.row.data.witnessUserName }}({{ scope.row.data.witnessUserCode }})
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="witnessStartTime" label="见证开始时间" min-width="110">
                  <template slot-scope="scope">
                    <div v-if="scope.row.data.witnessStartTime" class="format-time">
                      <div v-for="item in scope.row.data.witnessStartTime.split(' ')" :key="item">
                        {{ item }}
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="data.witnessEndTime" label="见证结束时间" min-width="110">
                  <template slot-scope="scope">
                    <div v-if="scope.row.data.witnessEndTime" class="format-time">
                      <div v-for="item in scope.row.data.witnessEndTime.split(' ')" :key="item">
                        {{ item }}
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="data.witnessAllocateUserName" label="分配人" min-width="80" />
                <el-table-column prop="data.witnessSubTaskAllocateTime" label="分配时间" min-width="110">
                  <template slot-scope="scope">
                    <div v-if="scope.row.data.witnessSubTaskAllocateTime" class="format-time">
                      <div v-for="item in scope.row.data.witnessSubTaskAllocateTime.split(' ')" :key="item">
                        {{ item }}
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <!--  -->
                <el-table-column label="操作" align="left" header-align="center" width="190">
                  <template slot-scope="scope">
                    <!-- 2.子任务按钮显示逻辑：
待分配：【分配见证人】
待见证：【更改见证人】
见证中：【进入见证】【更改见证人】
待审核：【审核见证记录】
已完成：【查看见证记录】 -->
                    <!-- v-if="scope.row.type == 'start'" -->
                    <template v-for="item in scope.row.pageOpers">
                      <!-- 工作人员-详情 -->
                      <el-button
                        v-if="item.code == 'OPERATE_VIEW_SUB_WITNESS_TASK_DETAIL'"
                        :key="item.code"
                        type="text"
                        size="default"
                        @click="recordShowFn(scope)"
                      >
                        详情
                      </el-button>
                      <el-button
                        v-if="item.code == 'OPERATE_VIEW_SUB_WITNESS_TASK_RECORD'"
                        :key="item.code"
                        type="text"
                        size="default"
                        @click="recordShowFn(scope)"
                      >
                        查看见证记录
                      </el-button>
                      <el-button
                        v-if="item.code == 'OPERATE_APPROVE_WITNESS_RECORD'"
                        :key="item.code"
                        type="text"
                        size="default"
                        @click="recordClickFn(scope)"
                      >
                        审核见证记录
                      </el-button>
                      <el-button
                        v-if="item.code == 'OPERATE_UPDATE_WITNESS_USER'"
                        :key="item.code"
                        type="text"
                        size="default"
                        @click="updateClickFn(scope)"
                      >
                        更改见证人
                      </el-button>
                      <el-button
                        v-if="item.code == 'OPERATE_ALLOCATE_WITNESS_USER'"
                        :key="item.code"
                        type="text"
                        size="default"
                        @click="allocateClickFn(scope)"
                      >
                        分配见证人
                      </el-button>
                      <el-button
                        v-if="item.code == 'OPERATE_ENTRY_WITNESS_SUB_TASK'"
                        :key="item.code"
                        type="text"
                        size="default"
                        @click="enterClickFn(scope)"
                      >
                        进入见证
                      </el-button>
                    </template>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="index" :index="indexFn" align="left" label="序号" width="50">
          <template slot-scope="scope">
            {{ (pageObj.currentPage - 1) * pageObj.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="data.projectName" label="项目名称" min-width="220" />
        <el-table-column prop="data.bidSectionName" label="标段名称" min-width="220">
          <template slot-scope="scope">
            <span class="line2" :title="scope.row.data.bidSectionName">
              {{ scope.row.data.bidSectionName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="data.bidSectionCode" label="标段编号" min-width="120">
          <template slot-scope="scope">
            <span class="line2" :title="scope.row.data.bidSectionCode">
              {{ scope.row.data.bidSectionCode }}
            </span>
          </template>
        </el-table-column>
        <!--        <el-table-column
          prop="data.sourceSystemName"
          label="项目来源"
          min-width="110"
        >
        </el-table-column>-->
        <el-table-column prop="data.bidOpenStartTime" label="开标时间" min-width="110">
          <template slot-scope="scope">
            <div v-if="scope.row.data.bidOpenStartTime" class="format-time">
              <div v-for="item in scope.row.data.bidOpenStartTime.split(' ')" :key="item">
                {{ item }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="data.bidOpenAddress" label="开标室" min-width="110">
          <!--          <template slot-scope="scope">
            <div class="format-time" v-if="scope.row.data.witnessStartTime">
              <div
                v-for="item in scope.row.data.witnessStartTime.split(' ')"
                :key="item"
              >
                {{ item }}
              </div>
            </div>
          </template>-->
        </el-table-column>
        <el-table-column prop="data.evaluationAddress" label="评标室" min-width="110">
          <!--          <template slot-scope="scope">-->
          <!--            <div class="format-time" v-if="scope.row.data.witnessEndTime">-->
          <!--              <div-->
          <!--                v-for="item in scope.row.data.witnessEndTime.split(' ')"-->
          <!--                :key="item"-->
          <!--              >-->
          <!--                {{ item }}-->
          <!--              </div>-->
          <!--            </div>-->
          <!--          </template>-->
        </el-table-column>
        <el-table-column prop="data.liveStatus" label="见证进度" width="160">
          <template slot-scope="scope">
            <div class="task-status">
              <span
                v-for="item in scope.row.data.witnessSubTaskStatusList"
                :key="item.witnessSubTaskId"
                :class="item.witnessSubTaskStatus"
              >
                {{ item.witnessSubTaskName }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" header-align="center" width="130">
          <template slot-scope="scope">
            <!-- 1.项目按钮显示逻辑
所有任务均为已完成：【详情】【查看见证书】
存在任务状态为非“已完成状态”：【详情】【取消见证】
-->
            <!-- {{ scope.row.pageOpers }} -->
            <template v-for="item in scope.row.pageOpers">
              <el-button
                v-if="item.code == 'OPERATE_VIEW_WITNESS_TASK_DETAIL'"
                :key="item.code"
                type="text"
                size="default"
                @click="detailClickFn(scope)"
              >
                详情
              </el-button>
              <el-button
                v-if="item.code == 'OPERATE_CANCEL_WITNESS_TASK'"
                :key="item.code"
                type="text"
                size="default"
                @click="cancelWitnessFn(scope)"
              >
                取消见证
              </el-button>
              <el-button
                v-if="item.code == 'OPERATE_VIEW_WITNESS_TASK_BOOK'"
                :key="item.code"
                type="text"
                size="default"
                @click="showPdfWitnessFn(scope)"
              >
                查看见证书
              </el-button>
            </template>
            <el-button type="text" size="default" @click="enterMessageClickFn(scope)">查看信息记录</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="layout-footer ui-pt10">
      <!-- {{ pageObj.total + " " + pageObj.pageSize }} -->
      <pagination
        v-if="pageObj.total > pageObj.pageSizes[0]"
        :total="pageObj.total"
        :page.sync="pageObj.currentPage"
        :limit.sync="pageObj.pageSize"
        :page-sizes="pageObj.pageSizes"
        @pagination="taskListFn"
      />
    </div>
    <!-- 随机分配见证人 -->
    <!-- 定向分配见证人 -->
    <AssignDialog
      :show="assignShow"
      :type="assignType"
      :header-title="assignTitle"
      :data="assignData"
      :row-data="currentWitness"
      @close="assignCloseFn(arguments)"
      @submit="assignSubmitFn"
    />
    <!-- 见证记录 -->
    <WitnessRecord
      :id="currentWitness.witnessSubTaskId"
      :show="recordShow"
      :type="recordType"
      :header-title="recordTitle"
      :row-data="currentWitness"
      :data="recordData"
      :init-data="TASKOBJ"
      @close="recordCloseFn"
      @submit="recordSubmitFn"
    />
    <!-- 见证书 -->
    <el-dialog title="见证书" :visible.sync="pdfVisible" width="1000px" class="pdf-dialog" @close="pdfCloseFn">
      <WitnessPdf :show.sync="pdfVisible" :pdf-params="pdfParams" pdf-box-height="500px" />
    </el-dialog>
    <!-- 取消见证 -->
    <el-dialog
      title="取消见证"
      :visible.sync="cancelVisible"
      width="500px"
      class="cancel-dialog"
      @close="cancelCloseFn"
    >
      <div class="info">
        <i class="el-icon-warning" />
        取消见证后该项目将从任务列表中清除，且该项目所有见证数据将清空， 确定要取消吗？
      </div>
      <el-form
        ref="cancelForm"
        class="ui-mt10"
        :model="cancelForm"
        :rules="cancelRules"
        label-width="80px"
        :inline="false"
        size="normal"
      >
        <el-form-item label="验证码" required prop="code">
          <el-input v-model="cancelForm.code" class="ui-w100" />
          <span title="看不清？换一张" @click="refreshCode">
            <s-identify class="ui-w120" :identify-code="identifyCode" />
          </span>
          <el-button type="text" size="default" @click="refreshCode">看不清？换一张</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="primary" :loading="cancelLoading" @click="cancelSubmitFn">确定</el-button>
        <el-button @click="cancelVisible = false">取消</el-button>
      </span>
    </el-dialog>
    <!-- 提示 -->
    <el-dialog title="提示" :visible.sync="tishiVisible" width="500px" class="cancel-dialog" @close="tishiCloseFn">
      <div class="info">
        <i class="el-icon-warning" />
        是否批量审核当前勾选的所有见证记录？
      </div>
      <span slot="footer">
        <el-button type="primary" :loading="tishiLoading" @click="tishiSubmitFn">确定</el-button>
        <el-button @click="tishiVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  // import ExpertList from "./expertList.vue";
  // import expertSignIn from "./expertSignIn.vue";
  import {
    moduleInit,
    taskList,
    taskCancel,
    subtaskListAll,
    subtaskBatchReview
    // projectBookDetail,
    // projectBookDownload,
    // projectDetail
  } from "../../api/api.js";
  import { FindArrayFn as findArrayFn } from "../../utils/utils";
  import TopStatus from "../../components/TopStatus.vue";
  import AssignDialog from "../../components/dialog/AssignDialog.vue";
  // import WitnessRecord from "../../components/dialog/WitnessRecord.vue";
  import WitnessRecord from "../../components/dialog/WitnessRecord.vue";
  import SIdentify from "../../components/sidentify.vue";
  import WitnessPdf from "../../components/WitnessPdf"; // 见证书预览pdf组件
  export default {
    components: { TopStatus, AssignDialog, SIdentify, WitnessRecord, WitnessPdf },
    data() {
      // 验证码校验
      const validateCode = (rule, value, callback) => {
        if (value === "" || typeof value === "undefined") {
          callback(new Error("验证码不能为空"));
        } else if (value !== this.identifyCode) {
          callback(new Error("验证码不正确"));
        } else {
          callback();
        }
      };
      return {
        suffix: process.env.VUE_APP_PDF,
        multipleTaskSelection: [],
        multipleSubTaskSelection: [],
        activeName: "expertList",
        TASKOBJ: {},
        industryTypeArr: [],
        liveStatusArr: [],
        roomNameList: [],
        formSearch: {
          date: "",
          keyWord: "",
          industry: [],
          status: ""
        },
        rules: {
          // date: [{ required: true, message: "日期不能为空", trigger: "blur" }],
          // keyWord: [{ required: true, message: "key不能为空", trigger: "blur" }],
        },
        currentWitness: {},
        identifyCode: "",
        pdfVisible: false,
        pdfParams: {
          belongId: "", // 附件归属主键id——必传参数
          attachTypeCode: "WITNESS_BOOK" // 附件编码——必传参数(查看见证书code为：WITNESS_BOOK)
        }, // 查看见证书参数
        tishiLoading: false,
        tishiVisible: false,
        cancelLoading: false,
        cancelVisible: false,
        cancelForm: {},
        cancelRules: {
          // reason: [
          //   { required: true, message: "停止原因不能为空", trigger: "blur" },
          // ],
          code: [
            {
              validator: validateCode,
              trigger: "blur"
            },
            { required: true, message: "验证码不能为空", trigger: "change" }
          ]
        },
        tableData: [],
        recordShow: false,
        // currentWitness: {},
        recordData: [],
        recordTitle: "",
        recordType: "",
        assignShow: false,
        assignTitle: "",
        assignData: [],
        assignType: "",
        pageObj: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          pageSizes: [10, 20, 30]
        },
        pageSizes: [10, 20, 30],
        pickerOptions: {
          disabledDate(time) {
            console.log("tiem", time);
            return false;
            // return time.getTime() > Date.now();
          }
        }
      };
    },
    async created() {
      console.log(this.$route.query.id, "====返回");
      await this.moduleInitFn();
      await this.handleSearchFn();
    },
    methods: {
      // master复选框
      taskCheckboxSelectFn(row) {
        console.log("rowaaa22", row);
      },
      // 子任务转态 待分配 可选中
      hasStatusFn(str) {
        // "WITNESS_UN_REVIEWED"
        return this.assignData.some((item) => item.data.witnessSubTaskStatusEnum === str);
      },
      hasCheckedFn(status) {
        // <i class="UNASSIGNED"></i>待分配 </template
        // ><i class="ASSIGNED"></i>待见证 <i class="WITNESSING"></i>见证中
        // <i class="WITNESS_UN_REVIEWED"></i>待审核
        // <i class="WITNESS_FINISHED"></i>已完成
        const arr = ["UNASSIGNED", "WITNESS_UN_REVIEWED"];
        return arr.indexOf(status) > -1;
      },
      // sub复选框
      subCheckboxSelectFn(row) {
        return this.hasCheckedFn(row.data.witnessSubTaskStatusEnum);
      },
      // sub复选框
      subCheckboxSelectFns(row) {
        if (
          row.data.witnessSubTaskInfoList.data.some(
            (el) =>
              el.witnessSubTaskStatusEnum === "UNASSIGNED" || el.witnessSubTaskStatusEnum === "WITNESS_UN_REVIEWED"
          )
        ) {
          return true;
        }
        return false;
      },
      // 验证码开始
      refreshCode() {
        this.identifyCode = this.makeCode("1234567890", 4);
      },
      makeCode(o, l) {
        let code = "";
        for (let i = 0; i < l; i++) {
          code += o[this.randomNum(0, o.length)];
        }
        return code;
      },
      randomNum(min, max) {
        return Math.floor(Math.random() * (max - min) + min);
      },
      // 验证码结束
      // 主任务全选
      taskSelectAllClickFn(selection) {
        console.log("taskSelectAllClickFn", selection);
        this.multipleTaskSelection = selection;
        let arr = [];
        // 主任务selection的length为0：清空选中；大于0：全选
        if (selection.length) {
          this.tableData.forEach((item) => {
            arr = arr.concat(
              item.data.witnessSubTaskInfoList.result.filter((itemB) =>
                this.hasCheckedFn(itemB.data.witnessSubTaskStatusEnum)
              )
            );
          });
        }
        this.multipleSubTaskSelection = arr;
        this.assignData = arr;
        this.tableData.forEach((item, i) => {
          this.toggleSelection(this.multipleSubTaskSelection, i);
        });
      },
      // 子任务全选 ，后续传参方式要改造 by link 20211202
      subTaskSelectAllClickFn(selection, { row, $index }) {
        console.log("subTaskSelectAllClickFn", selection);
        console.log("row", row);
        // 判断selection中是否有row的子任务，有：全选；没有：清空选中
        const flag = selection.some((item) => item.data.witnessTaskId !== row.data.witnessTaskId);
        console.log("selection.length", selection.length);
        // if (!selection.length) {// 主任务有都选的情况不能判断
        let arr = [];
        if (flag || !selection.length) {
          // 清空
          this.$refs.taskTable.toggleRowSelection(this.tableData[$index], false);
          this.multipleTaskSelection = this.multipleTaskSelection.filter(
            (item) => item.data.witnessTaskId !== row.data.witnessTaskId
          );
          arr = this.multipleSubTaskSelection.filter((item) => item.data.witnessTaskId !== row.data.witnessTaskId);
        } else {
          this.$refs.taskTable.toggleRowSelection(this.tableData[$index], true);
          this.multipleTaskSelection.push(row);
          arr = this.multipleSubTaskSelection.concat(selection);
        }
        this.handleSubTaskSelectionChangeFn(arr, row.data.witnessTaskId);
      },
      // 子任务选择
      subTaskSelectClickFn(selection, row) {
        console.log("subselection", selection);
        console.log("subrow", row);
        // 判断row在不在selection
        let i = null; // 主任务下标
        let itemRow = null;
        this.tableData.forEach((item, index) => {
          const f = item.data.witnessSubTaskInfoList.result.some(
            (itemB) => itemB.data.witnessSubTaskId === row.data.witnessSubTaskId
          );
          if (f) {
            i = index;
            itemRow = item; // 当前数据行
          }
        });
        // 选中判断
        const checked = selection.some((item) => item.data.witnessSubTaskId === row.data.witnessSubTaskId);
        console.log("checked", checked);
        // 全选判断
        let checkedAll = true;
        let checkedCount = 0;
        // let checkCount = 0;
        // let check
        itemRow.data.witnessSubTaskInfoList.result.forEach((rowA) => {
          const f = selection.some((item) => item.data.witnessSubTaskId === rowA.data.witnessSubTaskId);
          if (this.hasCheckedFn(rowA.data.witnessSubTaskStatusEnum)) {
            // checkCount++;
            if (!f) {
              // 过滤不能选择的
              checkedAll = false;
            } else {
              checkedCount++;
            }
          }
        });
        console.log("i", i);
        // 修改父选中
        if (checkedAll || checkedCount > 0) {
          this.$refs["taskTable"].toggleRowSelection(this.tableData[i], true);
          const flag = this.multipleTaskSelection.some(
            (item) => item.data.witnessTaskId === this.tableData[i].data.witnessTaskId
          );
          if (!flag) {
            this.multipleTaskSelection.push(this.tableData[i]);
          }
        } else {
          // 取消
          this.$refs["taskTable"].toggleRowSelection(this.tableData[i], false);
          this.multipleTaskSelection = this.multipleTaskSelection.filter(
            (item) => item.data.witnessTaskId !== row.data.witnessTaskId
          );
        }
        // 全选、全消还要加
        let kxArr = selection.filter((item) => this.hasCheckedFn(item.data.witnessSubTaskStatusEnum));
        kxArr = kxArr.filter((item) => item.data.witnessTaskId === row.data.witnessTaskId);
        // console.log("kxArr", kxArr);
        // let selection = val.filter((item) => {
        //   return item.data.witnessTaskId != row.data.witnessTaskId;
        // });
        // this.multipleSubTaskSelection = this.multipleSubTaskSelection.filter(
        //   (item) => {
        //     return item.data.witnessTaskId != row.data.witnessTaskId;
        //   }
        // );
        this.handleSubTaskSelectionChangeFn(kxArr, row.data.witnessTaskId);
        // // if (!checked || !checkedAll) {
        // //   this.$refs["taskTable"].toggleRowSelection(this.tableData[i], false);
        // // } else {
        // //   this.$refs["taskTable"].toggleRowSelection(this.tableData[i], true);
        // // }
        // // 有选中，未全选
        // // console.log(
        // //   "this.$refs.taskTable.$el",
        // //   this.$refs.taskTable.$el.getElementsByClassName("el-table__body")[0]
        // //     .children[1].children
        // // );
        // let tableTr = this.$refs.taskTable.$el.getElementsByClassName(
        //   "el-table__body"
        // )[0].children[1].children;
        // console.log("tableTr", tableTr);
        // let arr = [];
        // for (let i = 0; i < tableTr.length; i++) {
        //   const ei = tableTr[i];
        //   if (ei.className != "") {
        //     arr.push(ei);
        //   }
        // }
        // console.log("checkedCount > 0 && checkCount > checkedCount");
        // console.log(checkedCount, checkCount, checkedCount);
        // 这里先注释，调试完放开
        // if (checkedCount > 0 && checkCount > checkedCount) {
        //   if (arr[i].className.indexOf("is-indeterminate") > -1) {
        //   } else {
        //     arr[i].className += " is-indeterminate";
        //   }
        // } else {
        //   arr[i].className = arr[i].className.replace(" is-indeterminate", "");
        //   // this.$set(this.tableData[i], "indeterminate", false);
        // }
      },
      tableRowClassName() {
        // { row, column, rowIndex, columnIndex }
        // if (row.indeterminate && columnIndex == 0) {
        //   return "is-indeterminate";
        // }
        return "";
      },
      // 主任务选择事件
      taskSelectClickFn(selection, row) {
        console.log("taskSelectClickFn", selection);
        // console.log("row", row);
        let i = null;
        this.tableData.forEach((item, index) => {
          if (row.data.witnessTaskId === item.data.witnessTaskId) {
            i = index;
          }
        });
        // console.log("i", i);
        // 选中判断
        // const checked = selection.some((item) => item.data.witnessTaskId == row.data.witnessTaskId);
        // change中赋值
        // this.multipleTaskSelection = selection;
        const f = selection.some((item) => row.data.witnessTaskId === item.data.witnessTaskId);
        this.$nextTick(() => {
          console.log("f", f);
          if (f) {
            this.toggleSelection(this.multipleSubTaskSelection, i);
          } else {
            this.$refs[`multipleTable_${i}`] && this.$refs[`multipleTable_${i}`].clearSelection();
          }
        });
        this.multipleTaskSelection = selection;
        // this.multipleSubTaskSelection = this.multipleSubTaskSelection.filter;
        console.log("handleTaskSelectionChangeFn", selection);
        console.log("row.data.witnessTaskId", row.data.witnessTaskId);
        let arr = [];
        if (f) {
          arr = row.data.witnessSubTaskInfoList.result;
        }
        this.handleSubTaskSelectionChangeFn(arr, row.data.witnessTaskId);
        // 这里需要改动------------------------
        // this.multipleSubTaskSelection = arr;
        // this.assignData = arr;
      },
      // 主任务表格多选
      handleTaskSelectionChangeFn(val) {
        console.log("val", val);
        // return
        // if (!val.length) {
        // }
        /* this.multipleTaskSelection = val;
        console.log("handleTaskSelectionChangeFn", val);
        let arr = [];
        this.multipleSubTaskSelection = [];
        this.multipleTaskSelection.forEach((item) => {
          // this.tableData.witnessSubTaskInfoList
          console.log("result", item.data.witnessSubTaskInfoList.result);
          // 过滤可选项
          arr = arr.concat(
            item.data.witnessSubTaskInfoList.result.filter((item) =>
              this.hasCheckedFn(item.data.witnessSubTaskStatusEnum)
            )
          );
        });
        console.log("arrList", arr);
        // 这里需要改动------------------------
        this.multipleSubTaskSelection = arr; */
        // this.assignData = arr;
        // this.$nextTick(() => {
        //   let f = selection.some((item) => {
        //     return row.data.witnessTaskId == item.data.witnessTaskId;
        //   });
        //   console.log("f", f);
        //   if (f) {
        //     this.toggleSelection(this.multipleSubTaskSelection, i);
        //   } else {
        //     this.$refs["multipleTable_" + i] &&
        //       this.$refs["multipleTable_" + i].clearSelection();
        //   }
        // });
      },
      // 子任务表格多选
      async handleSubTaskSelectionChangeFn(val, idOld) {
        console.log("---------子任务表格多选 start----------------");
        const selection = val.filter((item) => this.hasCheckedFn(item.data.witnessSubTaskStatusEnum));
        console.log("selection", selection);
        console.log("subval", val);
        let arr = [];
        let id = idOld;
        if (selection.length) {
          id = id || val[0].data.witnessTaskId;
        }
        // 过滤当前主任务
        arr = this.multipleSubTaskSelection.filter((item) => item.data.witnessTaskId !== id);
        console.log("arr 1", arr);
        // 重新插入选中的当前主任务的子任务
        await selection.forEach((valitem) => {
          const f = arr.some((item) => item.data.witnessSubTaskId === valitem.data.witnessSubTaskId);
          if (!f) {
            arr.push(valitem);
          }
        });
        await this.$nextTick(() => {
          let i = null;
          this.tableData.some((item, index) => {
            if (id === item.data.witnessTaskId) {
              i = index;
            }
          });
          const f = selection.some((item) => id === item.data.witnessTaskId);
          console.log("f 2", f);
          console.log("i 2", i);
          if (f) {
            this.toggleSelection(arr, i);
          } else {
            this.$refs[`multipleTable_${i}`] && this.$refs[`multipleTable_${i}`].clearSelection();
          }
        });
        console.log("arr 2", arr);
        this.multipleSubTaskSelection = arr;
        this.assignData = arr;
        // this.assignData = val;
        // console.log("---------子任务表格多选 end----------------");
      },
      toggleSelection(rows, i) {
        // console.log("rows", rows);
        // console.log("i", i);
        // 弹框中需要，遗留数据
        this.assignData = rows;
        if (i === null || !this.$refs[`multipleTable_${i}`]) {
          return;
        }
        // 这里需要加一个取消选中的---------------
        this.$nextTick(() => {
          if (rows.length) {
            rows.forEach((row) => {
              this.$refs[`multipleTable_${i}`].toggleRowSelection(row, true);
            });
          } else {
            this.$refs[`multipleTable_${i}`].clearSelection();
          }
        });
      },
      // table 展开收起
      expandChangeFn(row, expandedRows) {
        // 展开：回调的第二个参数为 expandedRows；
        // 参数 row 在 expandedRows 中为展开，不在为收起
        // 所有展开行，数组最后一个是新展开的
        console.log("row", row);
        console.log("expandedRows", expandedRows);
        if (!expandedRows.length) {
          return;
        }
        const foldFlag = expandedRows.some(
          (item) =>
            // return item.data.projectCode == row.data.projectCode;
            item.data.witnessTaskId == row.data.witnessTaskId
        );
        let i = null;
        if (foldFlag) {
          this.tableData.forEach((item, index) => {
            if (item.data.witnessTaskId == row.data.witnessTaskId) {
              i = index;
            }
          });
        }
        console.log("-------------1", i);
        this.$nextTick(() => {
          if (i !== null) {
            this.toggleSelection(this.multipleSubTaskSelection, i);
            console.log("-------------2");
          }
        });
        if (!row.children) {
          // let o = {
          //   witnessTaskId: row.witnessTaskId,
          // };
          // let index = "";
          // this.tableData.some((item, i) => {
          //   if (item.witnessTaskId === row.witnessTaskId) {
          //     index = i;
          //     return;
          //   }
          // });
          // console.log("index", index);
          // this.subtaskListAllFn(o, index);
        } else {
          // 判断展开，反显选中的数据行
          // this.
        }
      },
      // 批量审核-提交
      tishiSubmitFn() {
        this.tishiLoading = true;
        this.subtaskBatchReviewFn();
        // this.taskCancelFn();
        // this.tishiVisible = false;
      },
      // 取消见证-提交
      cancelSubmitFn() {
        this.$refs["cancelForm"].validate((valid) => {
          if (valid) {
            if (this.cancelForm.code === this.identifyCode) {
              this.cancelLoading = true;
              console.log("111");
              this.taskCancelFn();
            }
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      // 提示
      tishiCloseFn() {
        this.tishiVisible = false;
      },
      // 见证书
      pdfCloseFn() {
        this.pdfVisible = false;
      },
      // 取消见证-提交
      cancelCloseFn() {
        this.cancelVisible = false;
      },
      // 取消见证接口 ---接口需要改动 by link 20211110
      async taskCancelFn() {
        try {
          const p = {
            witnessTaskId: this.currentWitness.witnessTaskId
          };
          console.log("p", p);
          const res = await taskCancel(p);
          if (res.success) {
            this.cancelVisible = false;
            this.cancelLoading = false;
            this.handleSearchFn();
            this.$message({
              type: "success",
              message: res.message || "操作成功",
              single: true
            });
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      // 任务状态
      witnessSubTaskStatusFn(val) {
        const array = this.TASKOBJ.witnessSubTaskStatus;
        const obj = findArrayFn(array, val) || {};
        return obj.label;
      },
      witnessItemStatusFn(val) {
        const array = this.TASKOBJ.witnessItemStatus;
        const obj = findArrayFn(array, val) || {};
        return obj.label;
      },
      // 行业类型转文字
      industryFn(val) {
        const array = this.TASKOBJ.industryTypeAndIndustry;
        const obj = findArrayFn(array, val) || {};
        return obj.label;
      },
      // 随机分配
      randomAssignFn() {
        // 如果有待审核
        const flag = this.hasStatusFn("WITNESS_UN_REVIEWED");
        if (flag) {
          this.$message({
            type: "error",
            message: '请取消勾选非"待分配"状态的见证任务后，重新进行操作。'
          });
          return;
        }
        this.assignShow = true;
        this.assignType = "random";
      },
      // 定向分配
      orientationAssignFn() {
        // 如果有待审核
        const flag = this.hasStatusFn("WITNESS_UN_REVIEWED");
        if (flag) {
          this.$message({
            type: "error",
            message: '请取消勾选非"待分配"状态的见证任务后，重新进行操作。'
          });
          return;
        }
        this.assignShow = true;
        this.assignType = "";
      },
      // 批量审核
      batchApproveFn() {
        //   let arr = ["UNASSIGNED",'WITNESS_UN_REVIEWED'];
        // 如果有待分配
        const flag = this.hasStatusFn("UNASSIGNED");
        if (flag) {
          this.$message({
            type: "error",
            message: '请取消勾选非"待审核"状态的见证任务后，重新进行操作。'
          });
        } else {
          this.tishiVisible = true;
        }
        // 提交批量审核
      },
      assignSubmitFn() {},
      assignCloseFn(arg) {
        if (arg[0] === "save") {
          this.handleSearchFn();
        }
        this.assignShow = false;
        this.assignTitle = "";
        this.assignType = "";
      },
      recordSubmitFn() {
        // 刷新列表
        this.taskListFn();
      },
      recordCloseFn() {
        this.recordShow = false;
        this.recordTitle = "";
        this.recordType = "";
      },
      indexFn(index) {
        return index + 1 + (this.pageObj.currentPage - 1) * this.pageObj.pageSize;
      },
      async moduleInitFn() {
        const p = { moduleName: "TASK" };
        try {
          const res = await moduleInit(p);
          if (res.success) {
            this.TASKOBJ = res.data;
            for (const key in res.data.industryType) {
              if (Object.hasOwnProperty.call(res.data.industryType, key)) {
                const item = res.data.industryType[key];
                this.industryTypeArr.push({
                  label: item,
                  value: key
                });
              }
            }
            this.roomNameList = res.data.roomNameList;
            for (const key in res.data.liveStatus) {
              if (Object.hasOwnProperty.call(res.data.liveStatus, key)) {
                const item = res.data.liveStatus[key];
                this.liveStatusArr.push({
                  label: item,
                  value: key
                });
              }
            }
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      async handleSearchFn() {
        this.pageObj.total = 0;
        this.pageObj.currentPage = 1;
        this.multipleTaskObj = {};
        console.log("ddd");
        await this.taskListFn();
      },
      // 管理员任务列表
      async taskListFn() {
        this.multipleTaskSelection = [];
        this.multipleSubTaskSelection = [];
        this.assignData = [];
        // currentPage // 当前页数
        // endTime // 结束时间
        // industry // 枚举值: QT
        // industryType // 枚举值: GCJS,ZFCG,CQJY,TDJY,YPCG
        // pageSize  // 每页条数
        // search // 关键字搜索
        // startTime // 起始时间
        // tenderMode // 枚举值: PUBLIC_BIDDING,INVITE_BIDDING
        // witnessSubTaskStatus // 枚举值: UNASSIGNED,ASSIGNED,WITNESSING,WITNESS_FINISHED,WITNESS_UN_REVIEWED,WITNESS_PASS
        try {
          const obj = {};
          const industryList = [];
          const industryTypeList = [];
          this.formSearch.industry.forEach((item) => {
            if (!obj[item[0]]) {
              obj[item[0]] = 1;
              if (item[0] !== null) {
                industryTypeList.push(item[0]);
              }
            }
            if (item[1] !== null) {
              industryList.push(item[1]);
            }
          });
          const p = {
            currentPage: this.pageObj.currentPage, // 当前页数
            pageSize: this.pageObj.pageSize, // 每页条数
            industryList, // 行业类型
            industryTypeList, // 行业类型
            witnessSubTaskStatus: this.formSearch.status[0], // 见证状态
            search: this.formSearch.keyWord // 搜索
          };
          console.log("this.formSearch.date", this.formSearch.date);
          if (this.formSearch.date && this.formSearch.date.length) {
            p.startTime = `${this.formSearch.date[0]} 00:00:00`; // 起始时间
            p.endTime = `${this.formSearch.date[1]} 23:59:59`; //
          }
          const res = await taskList(p);
          if (res.success) {
            // this.tableData = res.data.data;
            if (res.data.data.length === 0 && this.pageObj.currentPage !== 1) {
              this.pageObj.currentPage = 1;
              this.$nextTick(() => {
                this.taskListFn();
              });
              return;
            }
            this.tableData = res.data.result;
            this.pageObj.total = res.data.pageBean.count;
            // if (this.tableData.length) {
            //   // 组件支持的有问题
            //   let o = {
            //     witnessTaskId: this.tableData[0].data.witnessTaskId,
            //   };
            //   // for (let i = 0; i < this.tableData.length; i++) {
            //   //   const ei = this.tableData[i];
            //   //   o = {
            //   //     witnessTaskId: this.tableData[i].data.witnessTaskId,
            //   //   };
            //   //   await this.subtaskListAllFn(o, i);
            //   // }
            // }
            // this.subtaskListAllFn(o, 0);
          } else {
            this.$message({
              type: "error",
              message: "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      // 子任务列表
      async subtaskListAllFn(p, index) {
        try {
          const res = await subtaskListAll(p);
          if (res.success) {
            this.$set(this.tableData[index].data, "children", res.data.result);
            // this.$nextTick(() => {
            //   this.$refs.taskTable.toggleRowExpansion(
            //     this.tableData[index],
            //     true
            //   );
            // });
          } else {
            this.$message({
              type: "error",
              message: "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      // 批量审核
      async subtaskBatchReviewFn() {
        const p = {
          witnessSubTaskIds: this.assignData.map((item) => item.data.witnessSubTaskId)
        };
        console.log("p", p);
        // return;
        try {
          const res = await subtaskBatchReview(p);
          if (res.success) {
            this.$message({
              type: "success",
              message: "操作成功",
              single: true
            });
            this.taskListFn();
          } else {
            this.$message({
              type: "error",
              message: "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
        this.tishiVisible = false;
        this.tishiLoading = false;
      },
      roomIdchangeFn() {
        this.handleSearchFn();
      },
      typeChangeFn() {
        this.handleSearchFn();
      },
      statusChangeFn() {
        this.handleSearchFn();
      },
      recordShowFn({ row }) {
        console.log("row", row);
        this.currentWitness = row.data;
        this.recordShow = true;
        this.recordTitle = "查看见证记录";
      },
      recordClickFn({ row }) {
        console.log("row", row);
        this.currentWitness = row.data;
        this.recordShow = true;
        this.recordTitle = "审核见证记录";
      },
      // 更改见证人
      updateClickFn({ row }) {
        this.currentWitness = row.data;
        this.assignShow = true;
        this.assignTitle = "更改见证人";
      },
      // 分配见证人
      allocateClickFn({ row }) {
        this.currentWitness = row.data;
        this.assignShow = true;
        this.assignTitle = "分配见证人";
      },
      // 进入见证
      enterClickFn({ row }) {
        console.log(row, "---------------------------------------");
        this.$router.push({
          name: "WitnessTable",
          query: { id: row.data.witnessSubTaskId }
        });
      },
      // 查看信息记录
      enterMessageClickFn({ row }) {
        this.$router.push({
          name: "MessageRecord",
          query: { id: row.data.witnessTaskId }
        });
      },
      cancelWitnessFn({ row }) {
        console.log("row", row.data);
        this.cancelVisible = true;
        this.currentWitness = row.data;
        console.log("row", row);
        this.refreshCode();
      },
      // 主任务
      detailClickFn({ row }) {
        this.currentWitness = row.data;
        this.recordShow = true;
        this.recordTitle = "详情";
      },
      showPdfWitnessFn({ row }) {
        // console.log("row", row);
        this.pdfParams.belongId = row.data.witnessTaskId;
        // this.pdfVisible = true;
        const pdfs = JSON.stringify(this.pdfParams);
        this.$router.push({
          name: "ViewingWitnessData",
          query: { id: pdfs }
        });
      },
      submitSearchFn() {
        this.handleSearchFn();
        // this.$refs["formSearchFn"].submit();
        // this.$refs["formSearch"].validate((valid) => {
        //   if (valid) {
        //     // alert("submit!");
        //   } else {
        //     console.log("error submit!!");
        //     return false;
        //   }
        // });
      }
    }
  };
</script>
<style lang="scss" scoped>
  .layout-search {
    display: flex;
    justify-content: space-between;
    // .search-btns {
    // }
    .form-search {
      flex: 1;
    }
  }
  .tag-list {
    padding: 0 10px 10px;
  }
  .cancel-dialog {
    .info {
      padding-left: 28px;
      position: relative;
      i {
        position: absolute;
        top: 0;
        left: 0;
        color: #e6ad00;
        font-size: 18px;
        vertical-align: top;
      }
    }
  }
  .pdf-iframe {
    width: 100%;
    height: 500px;
    // height: calc(100%-20);
  }
</style>
<style lang="scss">
  .el-table {
    .is-indeterminate {
      .is-checked {
        // .el-checkbox__input .el-checkbox__inner::before {
        //   // display: none;
        // }
        .el-checkbox__input .el-checkbox__inner::after {
          display: none;
        }
      }
      .el-checkbox__input .el-checkbox__inner {
        background-color: #fff;
        border-color: #1890ff;
      }
      .el-checkbox__input .el-checkbox__inner::before {
        position: absolute;
        display: block;
        background-color: #1890ff;
        height: 2px;
        transform: scale(0.5);
        left: 0;
        right: 0;
        top: 5px;
        content: "";
      }
    }
  }
  .print-iframe {
    display: none;
  }
  // 打印
  @media print {
    #app {
      display: none;
    }
    .print-iframe {
      display: block;
      width: 100%;
      height: 2000px;
    }
  }
  .pdf-dialog {
    .el-dialog__body {
      padding: 0;
    }
  }
</style>
